package org.chen.web.controller.admin;

import org.apache.ibatis.annotations.Param;
import org.chen.common.RespUtils;
import org.chen.model.Tags;
import org.chen.respmsg.RespEnum;
import org.chen.service.TagsService;
import org.chen.vo.RespBean;
import org.chen.vo.TagsInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/tags")
public class TagsController {
    @Autowired
    TagsService service;

    @GetMapping("/")
    public RespBean<List<TagsInfo>> getAllTags(){
        List<Tags> tags = service.getTagsByUid();
        List<TagsInfo> list=tags.stream().map(item->{
            TagsInfo info=new TagsInfo();
            BeanUtils.copyProperties(item,info);
            Long count = service.getArticleCountByTag(item.getId());
            info.setArticleCount(count);
            return info;
        }).collect(Collectors.toList());
        return RespUtils.result(list, RespEnum.SUCCESS);
    }

    @PostMapping("/")
    public RespBean<String> addTag(String tagName){
        if (service.addTag(tagName)==1){
            return RespUtils.result( RespEnum.INSERT_SUCCESS);
        }
        return RespUtils.result( RespEnum.INSERT_FAIL);
    }

    @DeleteMapping("/{ids}")
    public RespBean<String> delTag(@PathVariable("ids") String ids){
        if (StringUtils.isEmpty(ids)){
            return RespUtils.fail( "ids不能为空");
        }
        if (service.delTag(ids)){
            return RespUtils.result( RespEnum.DELETE_SUCCESS);
        }
        return RespUtils.result( RespEnum.DELETE_FAIL);
    }
}
